#include "common/assert.h"

#include <windows.h>
#include <dsound.h>

#include "directsound.h"
#include "main.h"

static IDirectSound8* g_sound;
static IDirectSoundBuffer8* g_buffer;

const int32 c_channels = 1;
const int32 c_frequency = 44100;
const int32 c_sample_len = 2; // sample length in bytes
const int32 c_sound_buf_bits = c_sample_len * 8;
const int32 c_sound_buf_size = 2 << 15;
const int32 c_sound_buf_mask = c_sound_buf_size - 1;

static WAVEFORMATEX c_wfx =
{
	WAVE_FORMAT_PCM,		// WORD        wFormatTag;         /* format type */
	c_channels,				//WORD        nChannels;          /* number of channels (i.e. mono, stereo...) */
	c_frequency,			//DWORD       nSamplesPerSec;     /* sample rate */
	c_frequency * c_channels * c_sample_len,	//DWORD       nAvgBytesPerSec;    /* for buffer estimation */
	c_channels * c_sample_len,	//WORD        nBlockAlign;        /* block size of data */
	c_sound_buf_bits,		//WORD        wBitsPerSample;     /* number of bits per sample of mono data */
	0						//WORD        cbSize;             /* the count in bytes of the size of */
							//                                /* extra information (after cbSize) */
};

static const DSBUFFERDESC c_dsbdesc =
{
	sizeof(c_dsbdesc),		//DWORD           dwSize;
	DSBCAPS_GLOBALFOCUS,	//DWORD           dwFlags;
	c_sound_buf_size,		//DWORD           dwBufferBytes;
	0,						//DWORD           dwReserved;
	&c_wfx,					//LPWAVEFORMATEX  lpwfxFormat;
	0,
};

void directsound_init()
{
	HRESULT result = DirectSoundCreate8(0, &g_sound, 0);
	ASSERT(result == DS_OK);

	g_sound->SetCooperativeLevel(g_hwnd, DSSCL_PRIORITY);

	IDirectSoundBuffer* tmp;
	result = g_sound->CreateSoundBuffer(&c_dsbdesc, &tmp, 0);
	ASSERT(result == DS_OK);
	result = tmp->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*) &g_buffer);
	ASSERT(result == DS_OK);
}

void directsound_deinit()
{
	g_buffer->Release();
	g_sound->Release();
}

void directsound_update()
{
}